package com.oa.tools.utils.http;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.oa.tools.TkMapper;
import com.oa.tools.entity.OrgElement;
import com.oa.tools.entity.Person;
import com.oa.tools.entity.Stamp;
import com.oa.tools.utils.ExcelUtil;
import com.oa.tools.utils.MailUtil;
import com.oa.tools.utils.ObjectUtil;
import com.oa.tools.utils.StringUtil;
import com.oa.tools.utils.SysConfig;
import com.oa.tools.utils.XmlUtil;

import tk.mybatis.mapper.entity.Example;

public class EKPRequestClient {
	public static final Logger logger = LoggerFactory.getLogger(EKPRequestClient.class);
	/**
	 * 创建新用户 OA账号和邮箱
	 * @param xmlStr     新入职表单内容xml
	 * @param id		   新入职流程ID，去重使用
	 * @param force		   是否强制覆盖执行
	 * @return
	 * @throws Exception
	 */
	public static Object[] createNewStaffAccountCore(String xmlStr,String id,TkMapper<OrgElement> orgElementDAO) throws Exception {
		
		try {
			String excelPath = SysConfig.getSysString("excel文件").replace(".", "_"+id+".");
			File oldFile = new File(excelPath);
			if(oldFile.exists()) {
				oldFile.renameTo(new File(excelPath.replace(".", "_bak"+System.currentTimeMillis()+".")));
			}
			
			Object[] result = parseStaffXml2DataList(xmlStr);
			
			List<List<String>> data = (List<List<String>>) result[1];
			if(orgElementDAO!=null) {
				for(int i=1;i<data.size();i++) {
					String code = data.get(i).get(2);
					Example per_exam = new Example(OrgElement.class);
					per_exam.createCriteria().andEqualTo("fdNo", code).andEqualTo("fdOrgType", 8L).andEqualTo("fdIsAvailable", (short)1);/*.andGreaterThan("docCreateTime", new Date(lastestDateMill))*/;
					List<OrgElement> objs = orgElementDAO.selectByExample(per_exam);
					if(objs!=null && objs.size()>0) {
						throw new RuntimeException("创建人员报错：重复工号："+code+"，流程id:"+id);
					}
				}
			}
			
			ExcelUtil.writeExcel(excelPath, "人员导入数据", data);

			EKPRequestClient.importNewPeople2Ekp(excelPath,SysConfig.getSysString("用户导入模板ID"));

			EKPRequestClient.pushLatestStaffInfo2KK();
			
			return result;
		}catch(Throwable t) {
			logger.info("创建OA账号或邮箱失败：");
			logger.error("创建OA账号或邮箱失败：", t);
			throw t;
		}
	}

	/**
	 * 解析员工xml信息到Excel文件中去
	 * @param xmlStr
	 * @param excelPath
	 * @throws Exception
	 */
	public static Object []  parseStaffXml2DataList(String xmlStr) throws Exception {
		List<List<String>> datas = new ArrayList<>();
		List<String> titles = new ArrayList<>();
		titles.add("登录名(*)");
		titles.add("姓名(*)");
		titles.add("编号");
		titles.add("性别");
		titles.add("邮件地址");
		titles.add("手机号码");
		titles.add("所在部门.名称");
		titles.add("密码");
		titles.add("办公电话");
		datas.add(titles);
		
		Map<String,String> tableMap = SysConfig.getMap("新入职流程处理配置", "新入职字段");
		Set<String> regexSet = SysConfig.getSet("新入职流程处理配置", "重要岗位匹配规则");
		
		StringBuilder message = new StringBuilder();
		String result_new_xmlstr = XmlUtil.parseXml2StaffMap(xmlStr, (String) tableMap.get("明细表"),
				new XmlUtil.XMLHandler() {
					public void hanle(Node staff_node) throws Exception {
						List<Node> staff_ele_nodes = staff_node.selectNodes("void");
						Map<String, String> staffMap = new HashMap<>();
						Node emailnode = null;
						Node lognode = null;
						Node namenode = null;

						for (Node staff_ele_node : staff_ele_nodes) {
							String key = staff_ele_node.selectSingleNode("string[1]").getText();

							Node node = staff_ele_node.selectSingleNode("string[2]");
							String value = "";
							if (node == null) {
								node = staff_ele_node.selectSingleNode("object/long");
								if (node == null) {
									node = staff_ele_node.selectSingleNode("null");
									if (node == null) {
										node = staff_ele_node.selectSingleNode("object/void[2]/string[2]");
									}
								}
							}
							if (node != null) {
								value = node.getText();
							}

							if (((String) tableMap.get("邮箱")).equals(key))
								emailnode = node;
							else if (((String) tableMap.get("登录名")).equals(key)) {
								lognode = node;
							}
							else if (((String) tableMap.get("姓名")).equals(key)) {
								namenode = node;
							}

							staffMap.put(key, value);
						}

						String name = (String) staffMap.get(tableMap.get("姓名"));
						if ((name == null) || (name.length() == 0)) {
							return;
						}
						name=name.replaceAll("[^\\u4e00-\\u9fa5]", "");
						String dep = (String) staffMap.get(tableMap.get("部门"));
						String dep_child = (String) staffMap.get(tableMap.get("门店"));
						String gender = (String) staffMap.get(tableMap.get("性别"));
						String mobile = (String) staffMap.get(tableMap.get("手机"));
						String code = (String) staffMap.get(tableMap.get("工号"));
						String tel = (String) staffMap.get(tableMap.get("固话"));
						String position = (String) staffMap.get(tableMap.get("岗位"));

						
						for(String regex:regexSet) {
							if(position.matches(regex)) {
								message.append(dep+":"+name+"需要维护岗位："+position+"\r\n");
							}
						}
						
						tel = tel == null ? "" : tel.replaceAll("[^\\d]+", "").trim();
						if (tel.length() == 4) {
							tel = "6629" + tel;
						}

						if (!StringUtil.isBlank(dep_child)) {
							dep = dep + "-" + dep_child;
							if (!dep.endsWith("门店")) {
								dep = dep + "门店";
							}
						}
						
						mobile = mobile.replaceAll("[^0-9]", "");

						String logname = MailUtil.createEmail2Ok(name, dep, position, mobile, tel, code,
								gender);
						List<String> data = new ArrayList<String>();
						data.add(logname);
						data.add(name);
						data.add(code);						
						data.add(gender);
						data.add(logname + "@fengbangleasing.com");
						data.add(mobile);
						data.add(dep);
						data.add("Fb"+mobile.trim());
						data.add(tel);
						datas.add(data);

						emailnode.setName("string");
						emailnode.setText(logname + "@fengbangleasing.com");
						lognode.setName("string");
						lognode.setText(logname);
						namenode.setName("string");
						namenode.setText(name);
						
					}
				});
		
		logger.info(datas.toString().replace("], [", "]\r\n["));
		return new Object[] {result_new_xmlstr,datas,message.toString()};
	}

	/**
	 * EKP向KK同步
	 * @throws Exception
	 */
	public static String pushLatestStaffInfo2KK() throws Exception {
		String[] bodyString = OKHttpClientUtil.httpGet("http://oa.fengbangleasing.com:8020/kk/login.jsp", null, null);
		String cookieStr = bodyString[1].toString();
		Set<String> cookies = OKHttpClientUtil.parse2Cookies(cookieStr);

		Map<String, String> params = new HashMap<String, String>();
		params.put("j_username", SysConfig.kkConsoleUser);
		params.put("j_password", SysConfig.kkConsolePass);
		params.put("j_redirectto", "http://oa.fengbangleasing.com:8020/kk/index.jsp");

		bodyString = OKHttpClientUtil.httpPost("http://oa.fengbangleasing.com:8020/kk/j_acegi_security_check", params,
				cookies);

		bodyString = OKHttpClientUtil
				.httpGet("http://oa.fengbangleasing.com:8020/kk/kk/console/index.jsp?licenseFlag=true", null, cookies);

		params = new HashMap<String, String>();
		params.put("s_bean", "kkAdminConfigService");
		params.put("corpId", "1");
		params.put("type", "incre");
		bodyString = OKHttpClientUtil.httpPost("http://oa.fengbangleasing.com:8020/kk/sys/common/dataxml.jsp", params,
				cookies);
		logger.info(bodyString[0]);
		logger.info(bodyString[1]);
		return bodyString[0];
	}

	

	/**
	 * 导入新用户
	 * @param excelPath		导入文件
	 * @param impTemplateId  导入模板ID
	 * @throws Exception
	 */
	public static String importNewPeople2Ekp(String excelPath,String impTemplateId) throws Exception {
		Map<String, String> params = new HashMap<String, String>();
		params.put("j_username", SysConfig.ekpUser);
		params.put("j_password", SysConfig.ekpPass);

		String[] bodyString = OKHttpClientUtil.httpPost(SysConfig.domainName + "/j_acegi_security_check", params,
				null);

		String cookieStr = bodyString[1].toString();
		Set<String> cookies = OKHttpClientUtil.parse2Cookies(cookieStr);

		bodyString = OKHttpClientUtil.httpGet(SysConfig.domainName + "/sys/portal/page.jsp;" + bodyString[1], null,
				cookies);

		cookieStr = bodyString[1].toString();
		cookies.addAll(OKHttpClientUtil.parse2Cookies(cookieStr));

		String url1 = SysConfig.domainName
				+ "/sys/transport/sys_transport_import/SysTransportImport.do?method=view&fdId="+impTemplateId+"&fdModelName=com.landray.kmss.sys.organization.model.SysOrgPerson&type=";
		bodyString = OKHttpClientUtil.httpGet(url1, null, cookies);
		cookieStr = bodyString[1].toString();
		cookies.addAll(OKHttpClientUtil.parse2Cookies(cookieStr));

		String url = SysConfig.domainName
				+ "/sys/transport/sys_transport_import/SysTransportImportUpload.do?method=upload&fdModelName=com.landray.kmss.sys.organization.model.SysOrgPerson";
		File file = new File(excelPath);
		bodyString = OKHttpClientUtil.httpUploadExcel(url, null, cookies, file);
		
		logger.info(bodyString[0]);
		logger.info(bodyString[1]);
		return bodyString[0];
	}
	
	/**
	 * 禁用账号
	 */
	public static String invalidatePeople2Ekp(String personId) throws Exception {
		Map<String, String> params = new HashMap<String, String>();
		params.put("j_username", SysConfig.ekpUser);
		params.put("j_password", SysConfig.ekpPass);

		String[] bodyString = OKHttpClientUtil.httpPost(SysConfig.domainName + "/j_acegi_security_check", params,
				null);

		String cookieStr = bodyString[1].toString();
		Set<String> cookies = OKHttpClientUtil.parse2Cookies(cookieStr);

		bodyString = OKHttpClientUtil.httpGet(SysConfig.domainName + "/sys/portal/page.jsp;" + bodyString[1], null,
				cookies);

		cookieStr = bodyString[1].toString();
		cookies.addAll(OKHttpClientUtil.parse2Cookies(cookieStr));


		String url = SysConfig.domainName
				+ "/sys/organization/sys_org_person/sysOrgPerson.do?method=invalidatedAll&parent=&s_ajax=true";
		
		params.clear();
		params.put("List_Selected", personId);
		
		bodyString = OKHttpClientUtil.httpPost(url, params, cookies);
		
		logger.info(bodyString[0]);
		logger.info(bodyString[1]);
		return bodyString[0];
	}
	
	/**
	 *新增发票抬头
	 *
	 */
	public static String addFinacialCompany2Ekp(String companyName,String fdNumber,String order) throws Exception {
		Map<String, String> params = new HashMap<String, String>();
		params.put("j_username", SysConfig.ekpUser);
		params.put("j_password", SysConfig.ekpPass);

		String[] bodyString = OKHttpClientUtil.httpPost(SysConfig.domainName + "/j_acegi_security_check", params,
				null);

		String cookieStr = bodyString[1].toString();
		Set<String> cookies = OKHttpClientUtil.parse2Cookies(cookieStr);

		bodyString = OKHttpClientUtil.httpGet(SysConfig.domainName + "/sys/portal/page.jsp;" + bodyString[1], null,
				cookies);

		cookieStr = bodyString[1].toString();
		cookies.addAll(OKHttpClientUtil.parse2Cookies(cookieStr));


		String url = SysConfig.domainName
				+ "/fs/base/fs_base_project_accounting/fsBaseProjectAccounting.do?method=add&fdCompanyId=15f958979216a56bf12533440d89c01e&s_css=default";
		
		params.clear();
		bodyString = OKHttpClientUtil.httpGet(url, params, cookies);
		System.out.println(bodyString[0]);
		Pattern p = Pattern.compile("<input type=\"hidden\" name=\"fdId\" value=\"([a-z0-9]+?)\">");
		Matcher m = p.matcher(bodyString[0]);
		String fd_id = null;
		while(m.find()) {
			fd_id = m.group(1);
			break;
		}
		
		params.clear();
		
		params.put("fdCategoryId","163d3aa6a558ca53fc8980f4e91aed10");
		params.put("fdCategoryName","发票抬头");
		params.put("fdName",companyName);
		params.put("fdNumber",fdNumber);
		params.put("fdProjectManagerId","");
		params.put("fdProjectManagerName","");
		params.put("fdStartingTime","");
		params.put("fdProjectDept","");
		params.put("fdOrder",order);
		params.put("fdCompanyId","15f958979216a56bf12533440d89c01e");
		params.put("authReaderIds","");
		params.put("authReaderNames","");
		params.put("fdValidity","true");
		params.put("fdId",fd_id);
		params.put("method_GET","add");
		
		url = SysConfig.domainName
				+ "/fs/base/fs_base_project_accounting/fsBaseProjectAccounting.do?method=save&fdCompanyId=15f958979216a56bf12533440d89c01e&s_css=default";
		bodyString = OKHttpClientUtil.httpPost(url, params, cookies);
		
		logger.info(bodyString[0]);
		logger.info(bodyString[1]);
		return bodyString[0];
	}
	
	/**
	 *查询流程执行人
	 *
	 */
	public static Map<String,String> getFlowHandleFromEkp(String fdId) throws Exception {
		Map<String, String> params = new HashMap<String, String>();
		params.put("j_username", SysConfig.ekpUser);
		params.put("j_password", SysConfig.ekpPass);

		String[] bodyString = OKHttpClientUtil.httpPost(SysConfig.domainName + "/j_acegi_security_check", params,
				null);

		String cookieStr = bodyString[1].toString();
		Set<String> cookies = OKHttpClientUtil.parse2Cookies(cookieStr);

		bodyString = OKHttpClientUtil.httpGet(SysConfig.domainName + "/sys/portal/page.jsp;" + bodyString[1], null,
				cookies);

		cookieStr = bodyString[1].toString();
		cookies.addAll(OKHttpClientUtil.parse2Cookies(cookieStr));


		String url = SysConfig.domainName
				+ "/sys/common/dataxml.jsp?s_bean=lbpmHandlerParseService&modelId="+fdId+"&modelName=com.landray.kmss.km.review.model.KmReviewMain&analysis4View=false";
		
		params.clear();
		bodyString = OKHttpClientUtil.httpGet(url, params, cookies);
		System.out.println(bodyString[0]);
		logger.info(bodyString[0]);
		logger.info(bodyString[1]);
		
		Document document = XmlUtil.getDocument(bodyString[0]);
		Element root  = document.getRootElement();
		List<Element> children = root.elements();
		Map<String,String> nodeHandlerMap = new HashMap<>();
		for(Element child:children) {
			String key = child.attribute("nodeId").getText();
			String val = child.attribute("name").getText();
			nodeHandlerMap.put(key, val);
		}
		
		/*<dataList>
			<data nodeId="N2" name="杨佳伟"/>
			<data nodeId="N57" name="赵萌;郑煜华;邹仁凯;聂庆磊"/>
			<data nodeId="N64" name="乘用车-销售大区-东区-洛阳城市经理(杨佳伟)"/>
			<data nodeId="N65" name="乘用车-销售大区-东区区域总监(聂庆磊)"/>
			<data nodeId="N48" name="承贝;聂庆磊"/>
			<data nodeId="N49" name="承贝;聂庆磊"/>
			<data nodeId="N50" name="总经理(陈劲伟)"/>
			<data nodeId="N58" name="刁鹏"/>
			<data nodeId="N66" name="乘用车金融事业部负责人(岗位成员未设置)"/>
			<data nodeId="N54" name="暂时无法计算处理人"/>
		</dataList>*/
		
		return nodeHandlerMap;
	}
	
	public static String urlPost(String url, String param, Map<String, String> header) throws UnsupportedEncodingException, IOException {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        URL realUrl = new URL(url);
        // 打开和URL之间的连接
        URLConnection conn = realUrl.openConnection();
        //设置超时时间
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(15000);
        // 设置通用的请求属性
        if (header!=null) {
            for (Entry<String, String> entry : header.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // 获取URLConnection对象对应的输出流
        out = new PrintWriter(conn.getOutputStream());
        // 发送请求参数
        out.print(param);
        // flush输出流的缓冲
        out.flush();
        // 定义BufferedReader输入流来读取URL的响应
        in = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), "utf8"));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
        if(out!=null){
            out.close();
        }
        if(in!=null){
            in.close();
        }
        return result;
    }

	public static String addContact(String companyName,String fdNumber,String order) throws Exception {
		Map<String, String> params = new HashMap<String, String>();
		params.put("j_username", SysConfig.ekpUser);
		params.put("j_password", SysConfig.ekpPass);

		String[] bodyString = OKHttpClientUtil.httpPost(SysConfig.domainName + "/j_acegi_security_check", params,
				null);

		String cookieStr = bodyString[1].toString();
		Set<String> cookies = OKHttpClientUtil.parse2Cookies(cookieStr);

		bodyString = OKHttpClientUtil.httpGet(SysConfig.domainName + "/sys/portal/page.jsp;" + bodyString[1], null,
				cookies);

		cookieStr = bodyString[1].toString();
		cookies.addAll(OKHttpClientUtil.parse2Cookies(cookieStr));

		File dir = new File("");
		File children[] = dir.listFiles();
		for(File file:children) {
			long fsize = file.length();
			String getFileKeyUrl = SysConfig.domainName+"/sys/attachment/sys_att_main/sysAttMain.do?method=handleAttUpload&gettype=getuserkey&format=json&filesize="+fsize+"&md5=&s_ajax=true";
			bodyString = OKHttpClientUtil.httpGet(getFileKeyUrl, params, cookies);
			//{"status":"1","userkey":"S7gUNrrTenJTkTLs7%2FN0lBsnMDOmn2yZ3kIkS5Mq3kt0N5w8%2FxZniy5ZdFLhiOQc%0D"}
			
			Map<String, Object> userKeyMap= ObjectUtil.json2Map(bodyString[0]);
			String postFileUrl= SysConfig.domainName+"/sys/attachment/uploaderServlet?gettype=upload&format=json";
			Map<String, String> headerParam = new HashMap<String, String>();
			headerParam.put("userkey", userKeyMap.get("userkey").toString());
			bodyString = OKHttpClientUtil.httpUpload(postFileUrl, params, headerParam, cookies, file);
			//{"status":"1","filekey":"166fc586052a78ea732a6b7416bb1ad2"}
			String filekey=ObjectUtil.json2Map(bodyString[0]).get("filekey").toString();
		}
		
		
		String url = SysConfig.domainName
				+ "/fs/base/fs_base_project_accounting/fsBaseProjectAccounting.do?method=add&fdCompanyId=15f958979216a56bf12533440d89c01e&s_css=default";
		
		params.clear();
		bodyString = OKHttpClientUtil.httpGet(url, params, cookies);
		System.out.println(bodyString[0]);
		Pattern p = Pattern.compile("<input type=\"hidden\" name=\"fdId\" value=\"([a-z0-9]+?)\">");
		Matcher m = p.matcher(bodyString[0]);
		String fd_id = null;
		while(m.find()) {
			fd_id = m.group(1);
			break;
		}
		
		params.clear();
		
		params.put("fdCategoryId","163d3aa6a558ca53fc8980f4e91aed10");
		params.put("fdCategoryName","发票抬头");
		params.put("fdName",companyName);
		params.put("fdNumber",fdNumber);
		params.put("fdProjectManagerId","");
		params.put("fdProjectManagerName","");
		params.put("fdStartingTime","");
		params.put("fdProjectDept","");
		params.put("fdOrder",order);
		params.put("fdCompanyId","15f958979216a56bf12533440d89c01e");
		params.put("authReaderIds","");
		params.put("authReaderNames","");
		params.put("fdValidity","true");
		params.put("fdId",fd_id);
		params.put("method_GET","add");
		
		url = SysConfig.domainName
				+ "/fs/base/fs_base_project_accounting/fsBaseProjectAccounting.do?method=save&fdCompanyId=15f958979216a56bf12533440d89c01e&s_css=default";
		bodyString = OKHttpClientUtil.httpPost(url, params, cookies);
		
		logger.info(bodyString[0]);
		logger.info(bodyString[1]);
		return bodyString[0];
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println(addFinacialCompany2Ekp("测试发票抬头", "fbtt024", "24"));
	}
}